﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace BIN
{
    public delegate void SimpleDo();
    public enum DATEPART
    {
        DAY,
        HOUR,
        MINUTE,
        SECOND
    }
    public class StringCompareNoCase : IEqualityComparer<string>
    {
        public bool Equals(string t1, string t2)
        {
            return t1.Equals(t2, StringComparison.OrdinalIgnoreCase);
        }
        public int GetHashCode(string obj)
        {
            return obj.ToString().ToLower().GetHashCode();
        }
    }
    public static  class ShareMet
    {
        private static bool _callfromMainProg = false;
        /// <summary>
        /// 是否从主程序调用
        /// </summary>
        public static bool CallFromMainProg
        {
            get { return _callfromMainProg; }
            set { _callfromMainProg = value; }
        }
        private static readonly List<string> _ExceptFileFixxed
            = new List<string>() 
            {
             "AutoUpdate.exe","UserConfig.xml"
            };
        /// <summary>
        /// 固定排除的升级文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool FileIsFixedExcepted(string fileName)
        {
            return _ExceptFileFixxed.Contains(fileName,
                new StringCompareNoCase());
        }
        public static void CheckDir()
        {
            string appDir = ShareMet.GetAppDir();
            string tmpDir = ShareMet.CombineDir(appDir, "temp");
            CheckFolderExists(tmpDir);
            tmpDir=ShareMet.CombineDir(appDir,"Logs");
            CheckFolderExists(tmpDir);
        }
        public static void CheckDownUrl(ref string Url, ref string ToDir)
        {
            if (Url.StartsWith("\\\\"))
                Url = Url.Replace('/', '\\');
            else
                Url = Url.Replace('\\', '/');
            ToDir = ToDir.Replace('/', '\\');
        }
        private static  clsConfig _Config = null;
        public static clsConfig Config
        {
            get
            {
                if (null == _Config) _Config = new clsConfig();
                return _Config;
            }
        }
        public static void CheckFolderExists(string Folder)
        {
            if (!(System.IO.Directory.Exists(Folder))) System.IO.Directory.CreateDirectory(Folder);
        }
        public static void BeginProcess(string ProgName, string WorkDirectory)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            try
            {

                p.StartInfo.FileName = ProgName;
                if (WorkDirectory != "")
                    p.StartInfo.WorkingDirectory = WorkDirectory;
                p.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static bool UpdateListFileIsOk(string FullFileName)
        {
            if (!(ShareMet.FileExists(FullFileName))) return false;
            try
            {
                FileInfo fi = new FileInfo(FullFileName);
                return (Math.Abs(ShareMet.DateDiff(DATEPART.SECOND,
                    fi.LastWriteTime, DateTime.Now)) < 60);
            }
            catch
            {
                return false;
            }
        }
        public static bool IsUpdateAgent
        {
            get
            {
                try
                {
                    return (Config[CONFIG_KEY.IS_UPDATE_AGENT].Equals(
                        "YES", StringComparison.OrdinalIgnoreCase));
                }
                catch
                {
                    return false;
                }
            }
        }
        private static string _updateKey = string.Empty;
        /// <summary>
        /// 升级关键字如AGD
        /// </summary>
        public static string UpdateKey
        {
            get
            {
                if (string.IsNullOrEmpty(_updateKey))
                {
                    try
                    {
                        _updateKey = Config[CONFIG_KEY.UPDATE_KEY];
                    }
                    catch
                    {
                        _updateKey = string.Empty;
                    }
                }
                return _updateKey;
            }
        }
        public static string ShareFolder
        {
            get 
            {
                return (Config[CONFIG_KEY.SHARE_FOLDER].Trim());
            }
        }
        public static bool OnlyKeepMe
        {
            get
            {
                string val = Config[CONFIG_KEY.ONLY_KEEP_ME];
                return "Y".Equals(val, StringComparison.OrdinalIgnoreCase) ||
                    "1".Equals(val, StringComparison.OrdinalIgnoreCase) ||
                    "YES".Equals(val, StringComparison.OrdinalIgnoreCase);
            }
        }
        public static string GetAppDir()
        {
            string appDir = System.AppDomain.CurrentDomain.BaseDirectory;
            if (!appDir.EndsWith("\\")) appDir += "\\";
            return appDir;
        }
        public static string GetObjectString(object obj)
        {
            return ((obj == null || obj == DBNull.Value 
                || string.IsNullOrEmpty(obj.ToString()) ) ? string.Empty : obj.ToString());
        }
        public static bool FileExists(string FileName)
        {
            return (System.IO.File.Exists(FileName));
        }
        public static  string GetShortFileName(string FileName)
        {
            int Index = FileName.LastIndexOf('\\');
            if (Index < 0) return FileName;
            return FileName.Substring(Index + 1, FileName.Length - Index - 1);
        }
        private static string GetShortExec(string Prog)
        {
            int Pos = Prog.LastIndexOf(".");
            return (Pos > 0 ? Prog.Substring(0, Pos) : Prog);
        }
        /*
        public static string CombineDir(params string[] Para)
        {
            return System.IO.Path.Combine(Para);
        }
        */
        public static string CombineDir(string dir1, string dir2)
        {
            return System.IO.Path.Combine(dir1, dir2);
        }
        public static string CombineDir(string dir1, string dir2, string dir3)
        {
            return CombineDir(CombineDir(dir1, dir2), dir3);
        }
        public static double DateDiff(DATEPART dp, DateTime dt1, DateTime dt2)
        {
            TimeSpan t1 = new TimeSpan(dt1.Ticks);
            TimeSpan t2 = new TimeSpan(dt2.Ticks);
            TimeSpan Diff = t1.Subtract(t2).Duration();
            double Ret = 0;
            switch (dp)
            {
                case DATEPART.DAY:
                    Ret = (Diff.TotalDays);
                    break;
                case DATEPART.HOUR:
                    Ret = (Diff.TotalHours);
                    break;
                case DATEPART.MINUTE:
                    Ret = (Diff.TotalMinutes);
                    break;
                case DATEPART.SECOND:
                    Ret = (Diff.TotalSeconds);
                    break;
                default:
                    Ret = 0.0;
                    break;
            }
            bool Little = (dt2 < dt1);
            //return Ret;
            return (Little ? Ret * -1 : Ret);
        }
        /// <summary>
        /// 取程序名(去除路径，扩展名)
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string GetFileNameOnly(string fileName)
        {
            return GetShortExec(new System.IO.FileInfo(fileName).Name);
        }
        public static bool ProgRunned(string Prog, bool Kill)
        {
            string prog = GetShortExec(Prog);
            System.Diagnostics.Process[] mProcs =
                System.Diagnostics.Process.GetProcessesByName(prog);
            foreach (System.Diagnostics.Process sProc in mProcs)
            {
                if (string.Compare(sProc.ProcessName, prog, true) == 0)
                {
                    if (Kill) sProc.Kill(); //殺死進程
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 文件名是否相同
        /// </summary>
        /// <param name="fileName1"></param>
        /// <param name="fileName2"></param>
        /// <returns></returns>
        public static bool FileNameIsSame(string fileName1, string fileName2)
        {
            return (0 == string.Compare(fileName1, fileName2, true));
        }
        /// <summary>
        /// 带完全路径的程序名是否运行, c:\windows\system32\Notepad.exe
        /// </summary>
        /// <param name="ProgFullName"></param>
        /// <param name="Kill"></param>
        /// <returns></returns>
        public static bool ProgramRunned(string ProgFullName, bool Kill)
        {
            string Prog = GetFileNameOnly(ProgFullName);
            System.Diagnostics.Process[] mProcs =
                System.Diagnostics.Process.GetProcessesByName(Prog);
            if (null == mProcs || 0 == mProcs.Length) return false;
            bool Runned = false;
            int Count = mProcs.Length;
            for (int i = 0; i < Count; i++)
            {
                System.Diagnostics.Process proc = mProcs[i];
                if (FileNameIsSame(ProgFullName, proc.MainModule.FileName))
                {
                    Runned = true;
                    if (Kill) proc.Kill();
                }
            }
            return Runned;
        }
    }
}
